package a04_字符串;

/**
 * <p>
 * a04翻转字符串里的单词复习6
 * </p>
 *
 * @author flyduck
 * @since 2025/4/22
 */
public class a04_翻转字符串里的单词复习6 {

    public static void main(String[] args) {
        a04_翻转字符串里的单词复习6 test = new a04_翻转字符串里的单词复习6();
        test.reverseWords("  this  is  a  good  sample  ");
    }

    public String reverseWords(String s) {
        char[] oldChars = s.toCharArray();
        char[] newChars = removeAllSpaces(oldChars);

        reverse(newChars,0,newChars.length-1);

        reverseEachWord(newChars);

        return new String(newChars);
    }

    private void reverseEachWord(char[] chars) {
        int leftIdx = 0;
        int rightIdx = 0;
        while (rightIdx < chars.length){
            if(rightIdx == chars.length - 1 || chars[rightIdx + 1] == ' '){
                reverse(chars, leftIdx, rightIdx);
                rightIdx = rightIdx + 2;
                leftIdx = rightIdx;
            }else {
                rightIdx++;
            }
        }
    }

    private void reverse(char[] chars, int leftIdx, int rightIdx) {
        while (leftIdx < rightIdx){
            char temp = chars[leftIdx];
            chars[leftIdx] = chars[rightIdx];
            chars[rightIdx] = temp;
            leftIdx++;
            rightIdx--;
        }
    }

    private char[] removeAllSpaces(char[] oldChars) {
        int slowIdx = 0;
        int fastIdx = 0;
        while (fastIdx < oldChars.length){
            if(oldChars[fastIdx] != ' '){
                if(slowIdx != 0){
                    oldChars[slowIdx] = ' ';
                    slowIdx++;
                }
                while (fastIdx < oldChars.length && oldChars[fastIdx] != ' '){
                    oldChars[slowIdx] = oldChars[fastIdx];
                    slowIdx++;
                    fastIdx++;
                }
            }else {
                fastIdx++;
            }
        }
        char[] newChars = new char[slowIdx];
        System.arraycopy(oldChars, 0, newChars, 0, slowIdx);
        return newChars;
    }


}
